<template>
  <IndexIC
    v-if="state.deviceinfo.type === 'ic'"
    :deviceinfo="state.deviceinfo"
  ></IndexIC>
  <IndexPD
    v-else-if="state.deviceinfo.type === 'pd'"
    :deviceinfo="state.deviceinfo"
  ></IndexPD>
</template>
<script setup>
import IndexIC from "./indexic.vue";
import IndexPD from "./indexpd.vue";
import useUserStore from "@/store/modules/user";
import { devicelist } from "@/api/system/device.js";
import {
  ref,
  onMounted,
  onUnmounted,
  nextTick,
  reactive,
  getCurrentInstance,
} from "vue";

const devices = useUserStore().devices || {};
const state = reactive({
  devices: [],
  deviceinfo: {},
});
// 首先需要在组件中定义定时器变量
let rotationTimer = null;
// 启动设备轮播的函数
const startDeviceRotation = () => {
  // 清除已存在的定时器（如果有）
  clearDeviceRotation();

  // 设置新的定时器，每5秒切换一次设备
  rotationTimer = setInterval(() => {
    rotateDevices();
  }, 10000); // 5000毫秒 = 5秒
};

// 清除设备轮播定时器的函数
const clearDeviceRotation = () => {
  if (rotationTimer) {
    clearInterval(rotationTimer);
    rotationTimer = null;
  }
};

// 设备轮播逻辑函数
const rotateDevices = () => {
  if (!state.devices || state.devices.length <= 1) {
    return; // 如果没有设备或只有一个设备，则不需要轮播
  }

  // 找到当前设备在数组中的索引
  const currentIndex = state.devices.findIndex(
    (device) => device.id === state.deviceinfo.id
  );

  // 计算下一个设备的索引（循环）
  const nextIndex = (currentIndex + 1) % state.devices.length;

  // 设置下一个设备为当前显示的设备
  state.deviceinfo = state.devices[nextIndex];

  // 可以在这里添加设备切换时的其他逻辑，例如重新加载数据等
  console.log("设备已切换至:", state.deviceinfo.name);
};

onMounted(() => {
  devicelist({}).then((res) => {
    state.devices = res.filter((item) => useUserStore().devices[item.id]);
    if (state.devices[0]) {
      console.log(state.devices);
      state.deviceinfo = state.devices[0];

      // 启动设备轮播，每5秒切换一次设备
      startDeviceRotation();
    }
  });
});

onUnmounted(() => {
  state.devices = [];
  state.deviceinfo = {};

  // 清除定时器，防止内存泄漏
  clearDeviceRotation();
});
</script>
